package com.canyou.logback;

import ch.qos.logback.core.OutputStreamAppender;
import com.google.gson.Gson;
import lombok.Getter;
import lombok.Setter;
import lombok.SneakyThrows;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.ByteArrayOutputStream;

/**
 * logback钉钉appender
 *
 * @author fy
 * @date 20/07/22 11:05
 */
public class DingAppender<E> extends OutputStreamAppender<E> {

    private Gson gson = new Gson();
    private HttpClient client = HttpClients.createDefault();

    private int maxLength = 19000;
    private String url = "https://oapi.dingtalk.com/robot/send?access_token=";

    @Getter
    @Setter
    private String accessToken;

    @Override
    public void start() {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        this.setOutputStream(byteArrayOutputStream);
        url += accessToken;
        super.start();
    }

    @Override
    @SneakyThrows
    protected void subAppend(E event) {
        super.subAppend(event);
///        byte[] byteArray = this.encoder.encode(event);
///        String text = IOUtils.toString(byteArray, "UTF-8");
        String msg = getOutputStream().toString();
        // 截断到19099字符, 不然发不出去
        if (msg.length() > maxLength) {
            msg = msg.substring(0, maxLength);
        }
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-type", "application/json");
        httpPost.setEntity(new StringEntity(gson.toJson(DingMessage.defaultMessage(msg)), "UTF8"));
        EntityUtils.consume(client.execute(httpPost).getEntity());
    }

}
